package com.yfm.NettyServer;

import com.yfm.DiscoverInterface;
import com.yfm.DiscoverService;
import com.yfm.Rpc.Bean.RpcRequest;
import com.yfm.Rpc.Bean.RpcResponse;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.sendgrid.SendGridProperties;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

public class RpcProxy {

        private String serviceAddress;
        @Autowired
       private DiscoverInterface discoverInterface;

        public RpcProxy(String serviceAddress){
            this.serviceAddress = serviceAddress;
        }

        public <T> T create(final Class<?> aclass, final String serviceVersion){

            return (T) Proxy.newProxyInstance(
                    aclass.getClassLoader(),
                    new Class<?>[]{aclass},
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            RpcRequest rpcRequest = new RpcRequest();
                            rpcRequest.setRequestId(UUID.randomUUID().toString());
                                     //method.getDeclaringClass().getName()
                            rpcRequest.setInterfaceName(method.getDeclaringClass().getName());
                            System.out.println(method.getDeclaringClass().getName());
                            rpcRequest.setMethodName(method.getName());
                            rpcRequest.setParameters(args);
                            rpcRequest.setParameterTypes(method.getParameterTypes());

                            rpcRequest.setServiceVersion(serviceVersion);
                            String serviceName = aclass.getName();
                            if (serviceVersion!=null&&!serviceVersion.isEmpty()) {
                                serviceName += "-" + serviceVersion;
                            }

                           String address = discoverInterface.discover(serviceName);

                            if (address.isEmpty()) {
                                throw new RuntimeException("server address is empty");
                            }
                            // 从 RPC 服务地址中解析主机名与端口号
                            String[] array = address.split(":");
                            String ip = array[0];
                            int port = Integer.parseInt(array[1]);


                            RpcClient rpcClient = new RpcClient(ip,port);
                            RpcResponse rpcResponse = rpcClient.send(rpcRequest);
                            return rpcResponse.getResult();
                        }
                    }


            );

        }


}
